#import "WelcomeViewController.h"
#import "ScreenAdapter.h"
#import "RegLoginViewController.h"
#import "DBManager.h"
#import "MainViewCreater.h"
#import "ReloginWaitingViewController.h"

@interface WelcomeViewController ()
@property(retain,nonatomic) LeftViewController *leftViewController;
@end

@implementation WelcomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //配置当前显示的宣传页的张数
    page_nums = 3;
    
    [self showScrollView];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden=YES;
}

- (void)showScrollView {
    ScreenAdapter* screenAdapter = [ScreenAdapter getInstanse];
    
    CGFloat screen_width = screenAdapter.screenWidth;
    CGFloat screen_height = screenAdapter.screenHeight;
    
    UIScrollView *_scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    //设置UIScrollView 的显示内容的尺寸，有n张图要显示，就设置 屏幕宽度*n
    _scrollView.contentSize = CGSizeMake(screen_width * page_nums, screen_height);
    
    _scrollView.tag = 101;
    
    //设置翻页效果，不允许反弹，不显示水平滑动条，设置代理为自己
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.delegate = self;
    
    //在UIScrollView 上加入 UIImageView
    for (int i = 0 ; i < page_nums; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(screen_width * i , 0, screen_width, screen_height)];
        //将要加载的图片放入imageView中
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"wel%d.png",i+1]];
        imageView.image = image;
        
        //图片不出现缩放拉伸变形的代码
//        [imageView setContentScaleFactor:[[UIScreen mainScreen] scale]];
//        imageView.contentMode =  UIViewContentModeScaleAspectFill;
//        imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
//        imageView.clipsToBounds  = YES;
        
        [_scrollView addSubview:imageView];
        
        if (i == (page_nums - 1)) { //在最后一张图，增加进入按钮
            UIButton *button = [[UIButton alloc]init];
            [button setFrame:CGRectMake(0, 0, 200*screenAdapter.ratioWidth, 35*screenAdapter.ratioHeight)];
//            button.backgroundColor = [UIColor colorWithRed:252.0/255.0 green:74.0/255.0 blue:74.0/255.0 alpha:1];
            button.backgroundColor =RGBACOLOR(255, 255, 255, .5);
            button.layer.cornerRadius = 17.5*screenAdapter.ratioHeight;
            button.layer.borderColor = UIColorMake(237, 115, 26).CGColor;
            button.layer.borderWidth = 1.0;
            button.titleLabel.text = @"立即体验";
            button.titleLabel.font = [UIFont systemFontOfSize:20.0];
            [button setTitle:@"立即体验" forState:UIControlStateNormal];
            [button setTitleColor:UIColorMake(232, 94, 21) forState:UIControlStateNormal];
        

            button.center = CGPointMake(self.view.frame.size.width/2 +screen_width*i, self.view.frame.size.height - 55*screenAdapter.ratioHeight);
            [_scrollView addSubview:button];
            [button addTarget:self action:@selector(enterAppCallback) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    
    //初始化 UIPageControl 和 _scrollView 显示在 同一个页面中
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height-30);
    pageControl.numberOfPages = page_nums;//设置pageConteol 的page 和 _scrollView 上的图片一样多
    pageControl.tag = 201;
    pageControl.currentPageIndicatorTintColor = [UIColor darkGrayColor];
    pageControl.pageIndicatorTintColor=[UIColor grayColor];
    
    [self.view addSubview:_scrollView];
    [self.view addSubview:pageControl];
}

- (void)enterAppCallback{
    //此处进入登录首页
    NSLog(@"enter App from welcome splash view.");
    NSArray *user_info = [[DBManager getInstanse]selectFrom:@"myinfo" items:[NSArray arrayWithObjects:@"*", nil] limits:@"1"];
    UIViewController *mainViewController = [[MainViewCreater getInstance]createMainView];
    
    UIWindow *window = [[UIApplication sharedApplication]keyWindow];
    window.rootViewController = mainViewController;
    return;
    
    if (user_info.count == 0) {//用户未登录 进入登录注册界面
        //进入登录注册页面
        [self.navigationController pushViewController:[[RegLoginViewController alloc]init] animated:YES];
//        [self presentViewController: animated:YES completion:nil];
    }else{  //用户已经登录
        //此处需要判断用户是否已经登录，登录的用户不需要再次进入注册登录界面
        //判断当前登录的用户是谁,根据当前用户名username，去服务器上获取最新的数据，本地内存，数据库同步更新，最后进入主界面。
        //存在多用户的情况，但仅有一个用户的数据的hasLogin值是1（表示登录）
        NSMutableArray *info_array = [[DBManager getInstanse]selectFrom:@"myinfo" items:[NSArray    arrayWithObjects:@"hasLogin",@"id",@"level",@"access_token", nil] limits:@"1"];
        NSArray *temp_arr;
    
        BOOL hasLoginUser = false;
        NSString *uId,*utype,*utoken;
    
        for (temp_arr in info_array) {
            long hasLogin = [[temp_arr objectAtIndex:0]integerValue];
            if (hasLogin == 1) { //存在已经登录的用户
                //将已经登录的用户username发送到服务器，获取最新的用户信息，并同步到本地内存，数据库中，跳转到主界面。
                hasLoginUser = true;
                uId =[temp_arr objectAtIndex:1];
                utype =[temp_arr objectAtIndex:2];
                utoken =[temp_arr objectAtIndex:3];
                break;
            }
        }
        if (hasLoginUser == false) {
            [self.navigationController pushViewController:[[RegLoginViewController alloc]init] animated:YES];
//            [self presentViewController:[[RegLoginViewController alloc]init] animated:YES completion:nil];
        }else{
            if([utype integerValue] == 2) {
                utype = @"3";
            }else if([utype integerValue] == 3) {
                utype = @"2";
            }
            //存在已经登录的用户
            ReloginWaitingViewController* rwViewController =  [[ReloginWaitingViewController alloc]init];
            rwViewController.user_id = uId;
            rwViewController.user_type = utype;
            rwViewController.user_token = utoken;
            [self.navigationController pushViewController:rwViewController animated:YES];
//            [self presentViewController:rwViewController animated:YES completion:nil];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    // 记录scrollView 的当前位置，因为已经设置了分页效果，所以：位置/屏幕大小 = 第几页
    int current = scrollView.contentOffset.x/[UIScreen mainScreen].bounds.size.width;
    
    NSLog(@"Current Page:%d",current);
    //根据scrollView 的位置对page 的当前页赋值
    UIPageControl *page = (UIPageControl *)[self.view viewWithTag:201];
    page.currentPage = current;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)prefersStatusBarHidden{
    return YES;
}


@end
